package life.fairy.community.provider;

import com.alibaba.fastjson.JSON;
import life.fairy.community.dto.AccessTokenDTO;
import life.fairy.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GiteeProvider {
    /*
     * 获取accessToken字段，作为下一步请求的入参
     * 使用
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
        // 获取accessToken 字段的值
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//            String token = string.split("&")[0].split("=")[1];
            String token = string.split(",")[0].split(":")[1].replace("\"", "");
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 获取 gitee user相关信息
     * 通过okhttp创建get请求，直接传递accessToken获取 gitee 用户的user信息 json
     */
    public GiteeUser getUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .build();

        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
        }
        return null;
    }

}
